package com.mantisframework.core.base.service;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import jodd.util.StringUtil;

import org.springframework.stereotype.Service;

import com.mantisframework.core.base.dao.IBaseDao;
import com.mantisframework.core.page.PageBean;

/**
 * 功能：基础service实现类 作者：马东东 时间: 2010-3-24
 * 
 * @param <T>
 */
@Service
public abstract class BaseService<T> implements IBaseService<T> {
	@Resource
	private IBaseDao<T> baseDao;

	public boolean save(T pojo) {
		return this.baseDao.save(pojo);
	}

	public boolean delete(T pojo) {

		return this.baseDao.delete(pojo);
	}

	public boolean modify(T pojo) {

		return this.baseDao.modify(pojo);
	}
	
	public boolean saveOrUpdate(T pojo, Serializable id) {
		return this.baseDao.saveOrUpdate(pojo, id);
	}

	public PageBean getPojoAll(T pojo, Integer currentPage, Integer pageSize) {
		int totalRecord = this.baseDao.getCount(pojo);
		List<T> datas = this.baseDao.getAll(pojo, (currentPage - 1) * pageSize,
				pageSize);
		return new PageBean(currentPage, pageSize, totalRecord, datas);
	}

	public PageBean getPojoByCondition(T pojo, String condition,
			Integer currentPage, Integer pageSize) {
		int totalRecord = this.baseDao.getCount(pojo);
		List<T> datas = this.baseDao.getAll(pojo, condition, (currentPage - 1)
				* pageSize, pageSize);
		return new PageBean(currentPage, pageSize, totalRecord, datas);
	}

	public List<T> getPojoAll(T pojo, String condition) {
		if (StringUtil.isEmpty(condition)) {
			return this.baseDao.getAll(pojo);
		} else {
			return this.baseDao.getAll(pojo, condition, 0, 0);
		}

	}

	public PageBean getPojoAll(T pojo, PageBean pagebean) {
        
		int index = 0;// 起始位置
		int pageSize = 0;// 每页记录数

		if (pagebean != null) {
			pageSize = pagebean.getPageSize();
			index = pagebean.getIndex();
		}
		pagebean.setTotalRecord(this.baseDao.getCount(pojo));
		pagebean.setDatas(this.baseDao.getAll(pojo, index, pageSize));
		return pagebean;

	}

	public PageBean getPojoByCondition(T pojo, String condition,
			PageBean pagebean) {

		int index = 0;// 起始位置
		int pageSize = 0;// 每页记录数

		if (pagebean != null) {
			pageSize = pagebean.getPageSize();
			index = pagebean.getIndex();
		}
		pagebean.setTotalRecord(this.baseDao.getCount(pojo, condition));
		pagebean.setTotalPage(this.baseDao.getTotalPage(pojo, condition, pagebean.getPageSize()));
		pagebean
				.setDatas(this.baseDao.getAll(pojo, condition, index, pageSize));
		return pagebean;

	}


	public abstract T getPojoById(Serializable id);

	public IBaseDao<T> getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(IBaseDao<T> baseDao) {
		this.baseDao = baseDao;
	}

}
